<?php
namespace App\Http\Controllers;

use Curl\Curl;
use Illuminate\Http\Request;
use App\Models\Code;
use App\Events\SendMsg;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use App\Events\SendEmail;
use App\Models\Register;
use App\Models\User;
use Event;
/**
 *
 * @author Joker
 *        
 */
class SmsController extends Controller
{
    
    public function sendSms(Request $req) 
    {
       $code = get_rnd_num(6);
       $phone = $req->input('phone',0);
       $type = $req->input('type',0); //0 为注册验证码，1为找回密码验证码,2为修改密码
       if(empty($phone))
       {
           return jsonformat('error','手机号或邮箱不可为空！');
       }
       if(preg_match(config('app.phone_rule'),$phone))
       {
           $is_email = 0;
       }
       elseif (preg_match(config('app.email_rule'),$phone))
       {
           $is_email = 1;
       }
       else
       {
           return jsonformat('error','手机号或邮箱格式错误，请检查后重试');
       }
       if($type == 0){
           if($is_email == 1)
           {
               $hasUser = Register::where(['email'=>trim($phone)])->first();
               if($hasUser)
                   return jsonformat('error','该邮箱已被占用！');
           }
           else
           {
               $hasUser = Register::where(['phone'=>trim($phone)])->first();
               if ($hasUser)
                   return jsonformat('error','该手机已被占用！');
           }
       }
       $nowtime = date('Y-m-d H:i:s');
       $isConti = Code::where('created_at','<',date('Y-m-d H:i:s',time()))
                    ->where('created_at','>',date('Y-m-d H:i:s',strtotime("$nowtime - 1 minute")))
                    ->where('phone','=',$phone)->first();
       if(!empty($isConti))
           return jsonformat('error','短信或邮件已发送，请勿连续请求，谢谢！');
       $code = $this->checkCode($code, $phone,$is_email,$type);
       $content = $code;//'注册验证码'.$code.'【青苜网】';
       $attributes = array(
            'code'      => $code,
            'phone'     => $phone,
            'content'   => $content,
            'is_email'  => $is_email,
            'type'      => $type,
            'status'    => 0,
            'is_used'   => 0,
       );
       try {
        $sendCode = Code::firstOrCreate($attributes);
       }catch (\PDOException $e){
           Log::info(['验证码入库失败'=>$e->getMessage()]);
           return jsonformat('error','数据异常！');
       }
       if($is_email == 1)
       {
           Event::fire(new SendEmail($sendCode));
            return jsonformat('success','邮件已发送,请注意查收！');
       }
       else 
       {
           $sendCode->update(['status'=>1]);
           event(new SendMsg($sendCode));
           return jsonformat('success','短信已发送，请注意查收！');
       }
    }
    
    public function checkMsgCode(Request $req)
    {
        $data = $req->only('phone_code','verify_code','phone');
        $rules = ['verify_code' => 'required|captcha'];
        $validate = Validator::make($data,$rules);
        if(empty($data['phone']))
        {
            return jsonformat('error','手机号不可为空');
        }
        if(empty($data['phone_code']))
        {
            return jsonformat('error','手机或邮箱验证码不可为空');
        }

        $nowtime = date('Y-m-d H:i:s');
        $isConti = Code::where('created_at','<',date('Y-m-d H:i:s',time()))
                    ->where('created_at','>',date('Y-m-d H:i:s',strtotime("$nowtime - 10 minute")))
                    ->where(['phone'=>$data['phone'],'code'=>$data['phone_code'],'is_used'=>0])->first();
        if (empty($isConti))
        {
            return jsonformat('error','手机或邮箱验证码不正确！');
        }
        if($validate->fails())
        {
            return jsonformat('error','图形验证码不正确！');
        }
        return jsonformat('success','验证成功！');
    }
    
    private function checkCode($code,$phone,$is_email = 0 , $type = 0) {
        $isHas = Code::where(['phone'=>$phone,'code'=>$code,'is_email'=>$is_email,'type'=>$type])->first();
        if(!empty($isHas))
        {
            $code = get_rnd_num(6);
            $this->checkCode($code,$phone,$is_email , $type);
        }
        return $code;
    }
}
